import { View, Text, ScrollView } from "@tarojs/components";
import { useState, useEffect, useCallback, useRef } from "react";
import { AtModal, AtModalContent } from "taro-ui";
import Taro from '@tarojs/taro';
import { useRoomService } from '../../hooks/useRoomService';
// eslint-disable-next-line import/first
import { RoomResource, UserPanel, Card } from '@/types/global';

import Panel from "../components/panel";
import Cards from "../components/cards";
import BlackBag from "../components/blackBag";
import GemComponent from "../components/gem";
import GemModal from "../components/gemModel";
import BuyCardModal from "../components/buyCardModal";
import PlayerCards from "../components/playerCards";
import Operations from "../components/operations";
import CommandHistory, { CommandHistoryRef } from "../components/commandHistory";

import "./index.less";
import "./../../../node_modules/taro-ui/dist/style/components/modal.scss";


export default function Main() {
  const [catchGemModalState, setCatchGemModalState] = useState(false);
  const [playerCardsModal, setPlayerCardsModal] = useState<{isOpen: boolean, player: string}>({isOpen: false, player: ''});
  const [buyCardModalState, setBuyCardModalState] = useState(false); // 购买卡片弹窗状态
  const [roomId, setRoomId] = useState<string>(''); // 添加房间号状态
  const [playerIp, setPlayerIp] = useState<string>(''); // 当前玩家IP，默认为1
  const [opponentIp, setOpponentIp] = useState<string>(''); // 对手玩家IP，默认为12
  const [gameStatus, setGameStatus] = useState<string>('waiting'); // 游戏状态
  const [currentPlayerIp, setCurrentPlayerIp] = useState<string>('1'); // 当前回合玩家，默认为IP=1
  const [round, setRound] = useState<number>(0); // 回合数
  const [publicPrivilege, setPublicPrivilege] = useState<number>(0); // 公共特权数
  const [showBuyCard, setShowBuyCard] = useState<boolean>(false); // 是否显示购买卡片按钮
  const [showReserveCard, setShowReserveCard] = useState<boolean>(false); // 是否显示保留卡片按钮
  const [selectedCardId, setSelectedCardId] = useState<string | null>(null); // 当前选中的卡片ID
  const [selectedCard, setSelectedCard] = useState<Card | null>(null); // 当前选中的卡片对象
  const [maxGemsToTake, setMaxGemsToTake] = useState<number>(3); // 拿取宝石的最大数量
  const [allowedGemColors, setAllowedGemColors] = useState<string[] | undefined>(undefined); // 允许拿取的宝石颜色

  // 创建CommandHistory组件的引用
  const commandHistoryRef = useRef<CommandHistoryRef>(null);
  
  // 使用 useRoomService hook 来处理房间资源更新
  const { 
    roomResource, 
    // 移除connectWebSocket，因为应该复用已有的连接
    getRoomResource, // 确保获取房间资源的函数可用
    isConnected,
    connectionStatus,
    userIp,
    takeGems, // 获取拿取宝石的函数
    usePrivilege, // 使用特权的函数
    buyCard, // 购买卡片的函数
    buyCardWithGems, // 购买卡牌并使用宝石的函数
    reserveCard, // 保留卡片的函数
    refillGemBoard // 补充宝石盘的函数
  } = useRoomService({
    roomId, // 将roomId传递给useRoomService
    onRoomResourceUpdate: (resource: RoomResource) => {
      // console.log('📦 房间资源更新:', resource);
      // 更新房间资源状态
      handleRoomResourceUpdate(resource);
    },
    onRoomCommand: (cmd) => {
      console.log('即将打印接收的指令', cmd);
      // 通过引用向CommandHistory组件添加指令
      commandHistoryRef.current?.addCommand(cmd);
    }
  });

  // 页面加载时获取房间号并连接WebSocket
  useEffect(() => {
    // 获取页面参数中的房间号和玩家IP
    const router = Taro.getCurrentInstance().router;
    const roomIdParam = router?.params?.roomId;
    
    if (roomIdParam) {
      setRoomId(roomIdParam);
      setPlayerIp(userIp);
      // 直接获取房间资源，而不重新连接WebSocket
      getRoomResource(roomIdParam).then(result => {
        // 当通过HTTP获取到房间资源后，手动调用handleRoomResourceUpdate来初始化游戏状态
        if (result.success && result.data) {
          handleRoomResourceUpdate(result.data);
        }
      });
    }
  }, []);

  // 处理房间资源更新
  const handleRoomResourceUpdate = (resource: RoomResource) => {
    // 这里可以更新游戏界面的各个组件状态
    // 例如更新玩家面板、卡片塔、宝石盘等
    console.log('处理房间资源更新:', resource);
    
    // 更新游戏状态信息
    setGameStatus(resource.status);
    setCurrentPlayerIp(resource.currentPlayerIp);
    setRound(resource.round);
    setPublicPrivilege(resource.publicPrivilege);
    
    // 查找对手IP
    const otherPlayerIp = resource.playerIps.find(ip => ip !== playerIp);
    if (otherPlayerIp) {
      setOpponentIp(otherPlayerIp);
    }
  };

  const handleCloseCatchGemModal = () => {
    setCatchGemModalState(false);
  }

  const handleCloseBuyCardModal = () => {
    setBuyCardModalState(false);
  }

  const handleConfirmBuyCard = (gemIds: string[]) => {
    // 关闭弹窗
    setBuyCardModalState(false);
    
    // 执行购买操作
    if (selectedCardId) {
      if (gemIds.length === 0) {
        // 免费获取
        buyCard(playerIp, selectedCardId);
      } else {
        // 使用宝石支付
        buyCardWithGems(playerIp, selectedCardId, gemIds);
      }
      
      // 清空选中的卡片
      setSelectedCardId(null);
      setSelectedCard(null);
      setShowBuyCard(false);
      setShowReserveCard(false);
    }
  }

  const handleOpenPlayerCards = (player: string) => {
    setPlayerCardsModal({isOpen: true, player});
  }

  const handleClosePlayerCards = () => {
    setPlayerCardsModal({isOpen: false, player: ''});
  }

  // 获取指定IP的玩家面板数据
  const getPlayerPanel = (ip: string): UserPanel => {
    if (roomResource?.playerPanels && roomResource.playerPanels[ip]) {
      return roomResource.playerPanels[ip];
    }
    
    // 返回默认数据
    return {
      userIp: ip,
      score: ip === playerIp ? 15 : 12,
      crownsNum: ip === playerIp ? 2 : 1,
      collectedGems: [],
      ready: false,
      discountRed: ip === playerIp ? 1 : 0,
      discountBlue: ip === playerIp ? 0 : 1,
      discountGreen: ip === playerIp ? 2 : 1,
      discountWhite: ip === playerIp ? 0 : 2,
      discountBlack: ip === playerIp ? 1 : 0,
      gemNumRed: ip === playerIp ? 3 : 2,
      gemNumBlue: ip === playerIp ? 2 : 4,
      gemNumGreen: ip === playerIp ? 1 : 3,
      gemNumWhite: ip === playerIp ? 2 : 1,
      gemNumBlack: ip === playerIp ? 4 : 2,
      gemNumGold: ip === playerIp ? 1 : 2,
      gemNumPink: ip === playerIp ? 0 : 1,
      gemNumTotal: ip === playerIp ? 13 : 15,
      cardBought: [],
      cardKept: [],
      privilege: ip === playerIp ? 3 : 2
    };
  };

  // 检查玩家是否有足够的宝石购买卡片
  const hasEnoughGemsToBuyCard = (playerPanel: UserPanel, card: Card): boolean => {
    // 计算实际需要的宝石数量（扣除折扣后）
    const requiredRed = Math.max(0, card.costRed - playerPanel.discountRed);
    const requiredBlue = Math.max(0, card.costBlue - playerPanel.discountBlue);
    const requiredGreen = Math.max(0, card.costGreen - playerPanel.discountGreen);
    const requiredWhite = Math.max(0, card.costWhite - playerPanel.discountWhite);
    const requiredBlack = Math.max(0, card.costBlack - playerPanel.discountBlack);
    const requiredPink = Math.max(0, card.costPink); // 粉色宝石没有折扣

    // 检查各颜色宝石是否足够（金色宝石可以作为任意颜色使用）
    let goldUsed = 0;
    
    // 检查红色宝石
    if (playerPanel.gemNumRed < requiredRed) {
      const needed = requiredRed - playerPanel.gemNumRed;
      if (goldUsed + needed <= playerPanel.gemNumGold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足红色宝石
      }
    }
    
    // 检查蓝色宝石
    if (playerPanel.gemNumBlue < requiredBlue) {
      const needed = requiredBlue - playerPanel.gemNumBlue;
      if (goldUsed + needed <= playerPanel.gemNumGold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足蓝色宝石
      }
    }
    
    // 检查绿色宝石
    if (playerPanel.gemNumGreen < requiredGreen) {
      const needed = requiredGreen - playerPanel.gemNumGreen;
      if (goldUsed + needed <= playerPanel.gemNumGold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足绿色宝石
      }
    }
    
    // 检查白色宝石
    if (playerPanel.gemNumWhite < requiredWhite) {
      const needed = requiredWhite - playerPanel.gemNumWhite;
      if (goldUsed + needed <= playerPanel.gemNumGold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足白色宝石
      }
    }
    
    // 检查黑色宝石
    if (playerPanel.gemNumBlack < requiredBlack) {
      const needed = requiredBlack - playerPanel.gemNumBlack;
      if (goldUsed + needed <= playerPanel.gemNumGold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足黑色宝石
      }
    }
    
    // 检查粉色宝石
    if (playerPanel.gemNumPink < requiredPink) {
      const needed = requiredPink - playerPanel.gemNumPink;
      if (goldUsed + needed <= playerPanel.gemNumGold) {
        goldUsed += needed;
      } else {
        return false; // 金色宝石不够补足粉色宝石
      }
    }
    
    // 检查是否使用了过多的金色宝石
    if (goldUsed > playerPanel.gemNumGold) {
      return false;
    }
    
    return true;
  };

  // 获取当前玩家面板数据 (使用本设备的IP作为主人公IP，位于屏幕下方)
  const currentPlayerPanel = getPlayerPanel(playerIp);

  // 创建一个包装函数来调用 usePrivilege
  /* eslint-disable react-hooks/rules-of-hooks */
  const handleUsePrivilegeCallback = useCallback((ip: string, gemPositionIndex: number) => {
    usePrivilege(ip, gemPositionIndex);
  }, [usePrivilege]);
  /* eslint-enable react-hooks/rules-of-hooks */

  // 操作按钮的回调函数
  const handleUsePrivilege = () => {
    // 实现使用特权的逻辑
    console.log('使用特权');
    // 设置宝石选择参数：只能拿1个宝石，且只能拿金色宝石
    setMaxGemsToTake(1);
    setAllowedGemColors(undefined); // 设为默认参数
    // 打开宝石选择弹窗
    setCatchGemModalState(true);
  };

  const handleFillGemBoard = () => {
    // 实现补充宝石盘的逻辑
    console.log('补充宝石盘');
    refillGemBoard(playerIp);
  };

  const handleBuyCard = () => {
    // 实现购买卡片的逻辑
    console.log('购买卡片');
    // 如果选中了卡片，则打开购买卡片弹窗
    if (selectedCardId && selectedCard) {
      // 计算扣除折扣后需要的宝石数量
      const requiredRed = Math.max(0, selectedCard.costRed - currentPlayerPanel.discountRed);
      const requiredBlue = Math.max(0, selectedCard.costBlue - currentPlayerPanel.discountBlue);
      const requiredGreen = Math.max(0, selectedCard.costGreen - currentPlayerPanel.discountGreen);
      const requiredWhite = Math.max(0, selectedCard.costWhite - currentPlayerPanel.discountWhite);
      const requiredBlack = Math.max(0, selectedCard.costBlack - currentPlayerPanel.discountBlack);
      const requiredPink = Math.max(0, selectedCard.costPink); // 粉色宝石没有折扣

      const totalRequired = requiredRed + requiredBlue + requiredGreen + requiredWhite + requiredBlack + requiredPink;
      
      // 如果费用为0，则直接购买
      if (totalRequired === 0) {
        buyCard(playerIp, selectedCardId);
        // 清空选中的卡片
        setSelectedCardId(null);
        setSelectedCard(null);
        setShowBuyCard(false);
        setShowReserveCard(false);
      } else {
        // 否则打开宝石支付弹窗
        setBuyCardModalState(true);
      }
    }
  };

  const handleReserveCard = () => {
    // 实现保留卡片的逻辑
    console.log('保留卡片');
    if (selectedCardId) {
      // 设置宝石选择参数：只能拿1个宝石，且只能拿金色宝石
      setMaxGemsToTake(1);
      setAllowedGemColors(['gold']); // 只允许选择金色宝石
      // 打开宝石选择弹窗
      setCatchGemModalState(true);
    }
  };

  // 当玩家选择宝石完成后的回调函数
  // eslint-disable-next-line react-hooks/rules-of-hooks, react-hooks/exhaustive-deps
  const handleTakeGemsComplete = useCallback((ip: string, gemPositionIndices: number[]) => {
    // 如果是保留卡片时选择的金色宝石
    if (selectedCardId && allowedGemColors?.includes('gold') && gemPositionIndices.length === 1) {
      // 执行保留卡片操作
      reserveCard(ip, selectedCardId, gemPositionIndices[0]);
      // 清空选中的卡片
      setSelectedCardId(null);
      setShowBuyCard(false);
      setShowReserveCard(false);
    } 
    // 如果是使用特权时选择的金色宝石
    else if (allowedGemColors === undefined && gemPositionIndices.length === 1) {
      // 执行使用特权操作
      handleUsePrivilegeCallback(ip, gemPositionIndices[0]);
    }
    // 其他情况执行普通的拿取宝石操作
    else {
      takeGems(ip, gemPositionIndices);
    }
    
    // 重置宝石选择参数
    setMaxGemsToTake(3);
    setAllowedGemColors(['red', 'blue', 'green', 'white', 'black', 'pink']);
  }, [selectedCardId, allowedGemColors, playerIp, reserveCard, handleUsePrivilegeCallback, takeGems]);

  const handleTakeGems = () => {
    // 打开宝石选择弹窗（普通拿取宝石）
    setMaxGemsToTake(3);
    setAllowedGemColors(['red', 'blue', 'green', 'white', 'black', 'pink']);
    setCatchGemModalState(true);
  };

  // 当点击卡片时调用
  const handleCardClick = (card: Card) => {
    // 如果点击的是已选中的卡片，则取消选中
    if (selectedCardId === card.id) {
      setSelectedCardId(null);
      setSelectedCard(null);
      setShowBuyCard(false);
      setShowReserveCard(false);
    } else {
      // 否则选中该卡片
      setSelectedCardId(card.id);
      setSelectedCard(card);
      
      // 检查是否为等级四的卡片，如果是则无法购买和保留
      if (card.level === 4) {
        // 等级四的卡片无法购买和保留
        setShowBuyCard(false);
        setShowReserveCard(false);
      } else {
        // 检查玩家是否有足够的宝石购买这张卡片
        if (currentPlayerPanel && hasEnoughGemsToBuyCard(currentPlayerPanel, card)) {
          setShowBuyCard(true);
        } else {
          setShowBuyCard(false);
        }
        
        // 检查是否为保留卡片（通过检查是否在当前玩家的保留卡片列表中）
        const isReservedCard = getCurrentPlayerReservedCards().some(reservedCard => reservedCard.id === card.id);
        
        // 如果是保留卡片，则不能再次保留，只能购买
        if (isReservedCard) {
          setShowReserveCard(false);
        } else {
          // 检查是否可以保留卡片（宝石盘中有金色宝石）
          const goldGemCount = roomResource?.gemPositon?.filter(gemId => {
            if (gemId === "-1") return false;
            const gem = roomResource?.gemSource?.find(g => g.id === gemId);
            return gem?.color === 'gold';
          }).length || 0;
          
          if (goldGemCount > 0) {
            setShowReserveCard(true);
          } else {
            setShowReserveCard(false);
          }
        }
      }
    }
  };

  // 获取当前玩家的保留卡片
  const getCurrentPlayerReservedCards = (): Card[] => {
    if (roomResource?.playerPanels && roomResource.playerPanels[playerIp]) {
      return roomResource.playerPanels[playerIp].cardKept || [];
    }
    return [];
  };

  // 创建一个包含所有必要属性的roomResource对象
  const fullRoomResource = roomResource ? {
    ...roomResource,
    canUsePrivilege: true,
    canRefillGemBoard: true,
    canPerformMainAction: true
  } : null;

  return (
    <>
      <View className='mainContainer'>
        {/* 顶部玩家面板 (对手玩家) */}
        <Panel 
          className='panel-top' 
          isTop 
          onCardsClick={() => handleOpenPlayerCards('对手玩家')} 
          userPanel={getPlayerPanel(opponentIp)}
        />
        
        {/* 中间公共区域 */}
        <View className='content-container'>
          {/* 卡片塔区域 */}
          <Cards 
            cardListA={roomResource?.cardListA}
            cardListB={roomResource?.cardListB}
            cardListC={roomResource?.cardListC}
            cardListD={roomResource?.cardListD}
            currentPlayerIp={currentPlayerIp}
            currentPlayerPanel={currentPlayerPanel}
            hasEnoughGemsToBuyCard={hasEnoughGemsToBuyCard}
            onCardClick={handleCardClick}
            selectedCardId={selectedCardId || undefined}
            reservedCards={getCurrentPlayerReservedCards()} // 传递保留卡片数据
          />
          
          {/* 底部公共区域 */}
          <View className='content-container-bottom'>
            {/* 宝石盘区域 */}
            <GemComponent 
              click={() => setCatchGemModalState(true)} 
              gemPosition={roomResource?.gemPositon}
              gemSource={roomResource?.gemSource}
            />
            {/* 补充行动历史记录区域 */}
            <CommandHistory 
              ref={commandHistoryRef}
              onCommandReceived={(cmd) => {
                // 可以在这里添加额外的处理逻辑
                console.log('收到指令:', cmd);
              }}
            />
            
            {/* 黑袋区域 */}
            <BlackBag blackBag={roomResource?.blackBag} />
          </View>
          
          {/* 操作按钮区 */}
          {fullRoomResource && (
            <Operations 
              roomResource={fullRoomResource}
              currentPlayerIp={playerIp}
              onUsePrivilege={handleUsePrivilege}
              onFillGemBoard={handleFillGemBoard}
              onBuyCard={handleBuyCard}
              onReserveCard={handleReserveCard}
              onTakeGems={handleTakeGems}
              showBuyCard={showBuyCard}
              showReserveCard={showReserveCard}
            />
          )}
        </View>

        
        {/* 底部玩家面板 (当前玩家) - 主玩家面板位于屏幕下方 */}
        <Panel 
          className='panel-bottom' 
          onCardsClick={() => handleOpenPlayerCards('当前玩家')} 
          userPanel={getPlayerPanel(playerIp)}
        />
      </View>
      
      {/* 宝石选择弹窗 */}
      <AtModal isOpened={catchGemModalState}>
        <AtModalContent>
          <GemModal 
            close={handleCloseCatchGemModal} 
            gemSource={roomResource?.gemSource}
            gemPosition={roomResource?.gemPositon}
            currentPlayerIp={playerIp}
            onTakeGems={handleTakeGemsComplete}
            maxGemsToTake={maxGemsToTake}
            allowedGemColors={allowedGemColors}
          />
        </AtModalContent>
      </AtModal>
      
      {/* 购买卡片弹窗 */}
      <AtModal isOpened={buyCardModalState}>
        <AtModalContent>
          {selectedCard && (
            <BuyCardModal 
              close={handleCloseBuyCardModal} 
              card={selectedCard}
              userPanel={currentPlayerPanel}
              gemSource={roomResource?.gemSource}
              onConfirm={handleConfirmBuyCard}
            />
          )}
        </AtModalContent>
      </AtModal>
      
      {/* 玩家卡片弹窗 */}
      <PlayerCards 
        isOpen={playerCardsModal.isOpen} 
        onClose={handleClosePlayerCards} 
        playerName={playerCardsModal.player} 
        userPanel={playerCardsModal.player === '当前玩家' ? getPlayerPanel(playerIp) : getPlayerPanel(opponentIp)}
      />
    </>
  );
}